package com.ruoyi.admin.utils.qinniu;

import com.alibaba.fastjson2.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.uuid.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.qiniu.common.Zone;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;


import java.io.IOException;
import java.util.Objects;

/**
 * @author Shenjh
 * @version 1.0.0
 * @title QiniuService
 * @description <TODO description class purpose>
 * @date 2023/3/21 10:26
 */
@Component
public class QiniuService {
    private static final Logger logger = LoggerFactory.getLogger(QiniuService.class);

    // 设置好账号的ACCESS_KEY和SECRET_KEY
    @Value("${qiniu.access}")
    public String ACCESS_KEY = "LYk-xYVu7p_z74PoPKoipLQxjw2J8y_YIAHwddOH";
    @Value("${qiniu.secret}")
    public String SECRET_KEY= "E8wFX-E6HOttFUI8DnMA4_G8aPPfCPBPoxPGAXhk";
    // 要上传的空间
    String bucketname = "sjhwarehouse";

    // 密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    // 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
    Configuration cfg = new Configuration(Zone.zone2());
    // ...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);

    // 测试域名，只有30天有效期
    @Value("${qiniu.domain}")
    private static String QINIU_IMAGE_DOMAIN = "http://ru691gvt7.hn-bkt.clouddn.com/";

    // 简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    public String saveImage(MultipartFile file) throws IOException {
        try {
            int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
            String name = FileUploadUtils.extractFilename(file);
            if (fileNamelength < 0) {
                return null;
            }
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), name, getUpToken());
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                logger.error("七牛异常:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            logger.error("七牛异常:" + e.getMessage());
            return null;
        }
    }
}
